(function () {
	"use strict";
	const userName = document.querySelector('.userName'),
		userPass = document.querySelector('.userPass'),
		submit = document.querySelector('.submit');
	userName.focus();

	// 校验账号规则
	const validateName = (name) => {
		if (name.length === 0) {
			alert('账号不能为空!');
			return false;
		}
		let reg1 = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
		let reg2 = /^(?:(?:\+|00)86)?1\d{10}$/;
		let reg3 = /^(?:[\u4e00-\u9fa5·]{2,16})$/;
		if (!reg1.test(name) && !reg2.test(name) && !reg3.test(name)) {
			alert('账号格式不正确!');
			return false;
		}
		return true;
	};

	// 校验密码规则
	const validatePass = (password) => {
		if (password.length === 0) {
			alert('密码不能为空!');
			return false;
		}
		let reg = /^\w{6,16}$/;
		if (!reg.test(password)) {
			alert('密码格式有误!');
			return false;
		}
		return true;
	};

	// 登录提交
	let isRun;
	const submitHandle = async function submitHandle() {
		if (isRun) return;
		isRun = true;
		submit.style.background = "#CCC";

		let account = userName.value.trim(),
			password = userPass.value.trim();
		// 格式校验 & 密码加密
		if (!validateName(account) || !validatePass(password)) {
			isRun = false;
			submit.style.background = '#2299EE';
			return;
		}
		password = md5(password);
		try {
			// 向服务器发送请求
			let { code, token } = await http.post('/user/login', {
				account,
				password
			});
			// 处理请求结果:登录成功后，需要把token存储起来 & 提示 & 跳转
			if (+code !== 0) {
				alert('登录失败，请稍后再试~');
			} else {
				utils.storage.set('tk', token);
				alert('恭喜您，登录成功啦~');
				location.href = 'index.html';
			}
		} catch (_) { }

		isRun = false;
		submit.style.background = '#2299EE';
	};
	submit.onclick = submitHandle;
	userPass.onkeyup = function (ev) {
		// 按下Enter键登录
		if (ev.keyCode === 13) {
			submitHandle();
		}
	};
})();